﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WPFFollowPointer.Examples
{
    public partial class Example1
    {
        private Vector velocity = new Vector(0, 0);
        private TranslateTransform translation = new TranslateTransform();
        private Stopwatch stopwatch = new Stopwatch();
        private TimeSpan prevTime = TimeSpan.Zero;

        public Example1()
        {
            this.InitializeComponent();

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

            this.rectangle1.RenderTransform = this.translation;

            this.stopwatch.Start();
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {

            //上次绘制到此时的时间间隔
            TimeSpan currentTime = this.stopwatch.Elapsed;
            double elapsedTime = (currentTime - this.prevTime).TotalSeconds;
            this.prevTime = currentTime;

            //鼠标相对于小方块的位置
            Point mouseLoc = Mouse.GetPosition(this.rectangle1);
            //由于改相当位置是相对于小方块左上角的,将其纠正到相当于小方块中心
            mouseLoc.Offset(-this.rectangle1.ActualWidth / 2, -this.rectangle1.ActualHeight / 2);


            //使用鼠标相对于小方块的位置作为外力
            Vector force = new Vector(mouseLoc.X, mouseLoc.Y);

            //流动摩擦力系数假设为该值
            double coefficient = 5;

            //假设小方块质量为1,则加速度为a = force/1;
            //那么在elapsedTime内其速度的变化量为a*elapsedTime
            //由于流动摩擦力与速度成正比,那么流动摩擦力为coefficient * this.velocity
            //所以速度的变化为(force * 200 - coefficient * this.velocity) * elapsedTime
            //这里为了演示中小方块的速度更快一点,我们将外力扩大了200倍
            Vector velocityDelta = (force * 200 - coefficient * this.velocity) * elapsedTime;

            //当前速度
            this.velocity += velocityDelta;

            //小方块的新位置
            this.translation.X += this.velocity.X * elapsedTime;
            this.translation.Y += this.velocity.Y * elapsedTime;

        }

    }
}
